package com.jcl.cloud.common.service.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

public class HttpClientUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static RequestConfig requestConfig = null;
    private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static SSLConnectionSocketFactory sslsf = null;
    private static PoolingHttpClientConnectionManager cm = null;
    private static SSLContextBuilder builder = null;
    final static String ip = "forward.xdaili.cn";//这里以正式服务器ip地址为准
    final static int port = 80;//这里以正式服务器端口地址为准
    private static HttpHost proxy;

    //以下订单号，secret参数 须自行改动
    public  static String authHeader = authHeader("ZF2018321607932JieP", "2e1c0dbe58214987b9b92069524fea38", (int) (new Date().getTime()/1000));


    public static CloseableHttpClient httpClient = null;


    public static CloseableHttpClient httpClientNoProxy = null;

    static {
        try {
            proxy = new HttpHost(ip, port);
            // 配置超时时间（连接服务端超时1秒，请求数据返回超时2秒）
            requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)
                    .setConnectionRequestTimeout(80000).build();
            // 设置默认跳转以及存储cookie

            builder = new SSLContextBuilder();
            // 全部信任 不做身份鉴定
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(HTTP, new PlainConnectionSocketFactory())
                    .register(HTTPS, sslsf)
                    .build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(200);//max connection


            httpClientNoProxy = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .setConnectionManager(cm)
                    .setConnectionManagerShared(true)
                    .setDefaultRequestConfig(requestConfig)
                    .build();

            httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .setConnectionManager(cm)
                    .setConnectionManagerShared(true)
                    //.setProxy(proxy)
                    .setDefaultRequestConfig(requestConfig)
                    .build();

            //httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
           // httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);



        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static String getAuthHeader(){
        return  authHeader("ZF2018321607932JieP", "2e1c0dbe58214987b9b92069524fea38", (int) (new Date().getTime()/1000));
    }


    public static String authHeader(String orderno, String secret, int timestamp){
        //拼装签名字符串
        String planText = String.format("orderno=%s,secret=%s,timestamp=%d", orderno, secret, timestamp);

        //计算签名
        String sign = org.apache.commons.codec.digest.DigestUtils.md5Hex(planText).toUpperCase();

        //拼装请求头Proxy-Authorization的值
        String authHeader = String.format("sign=%s&orderno=%s&timestamp=%d", sign, orderno, timestamp);
        return authHeader;
    }

    public static CloseableHttpClient getHttpClient() throws Exception {

        return HttpClientUtil.httpClient;
    }

    public static String doGet(String url){

        String result = "";
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        HttpEntity resEntity = null;



        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000).build();
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");




        try {
            response = httpClientNoProxy.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                resEntity = response.getEntity();
                if (resEntity != null) {
                    //result = EntityUtils.toString(resEntity,"utf-8");
                    result =  JSON.parseObject(EntityUtils.toString(resEntity,"utf-8")).toJSONString();
                }
                logger.info("result = " + result);
            }else {
                logger.info("statusCode = " + statusCode);
            }
        } catch (Exception e) {
            logger.error("错误信息:",e);
        }finally {
            try {
                IOUtils.closeQuietly(response);
                httpGet.releaseConnection();
                EntityUtils.consume(resEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }



    public static String doPost(String urlPath, Map<String, String> map) throws Exception {

        String result = "";
        HttpPost httpPost = new HttpPost(urlPath);

        HttpEntity resEntity = null;


        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        HttpContext localContext = new BasicHttpContext();

        // 设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
            list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        if (list.size() > 0) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
        }

        CloseableHttpResponse response = null;
        try {
            response = httpClientNoProxy.execute(httpPost, localContext);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                resEntity = response.getEntity();
                if (resEntity != null) {
                    //result = EntityUtils.toString(resEntity,"utf-8");
                    result =  JSON.parseObject(EntityUtils.toString(resEntity,"utf-8")).toJSONString();
                }
                logger.info("result = " + result);
            }else {
                logger.info("statusCode = " + statusCode);
            }
        } catch (Exception e) {
            logger.error("错误信息:",e);
        }finally {
            try {
                IOUtils.closeQuietly(response);
                httpPost.releaseConnection();
                EntityUtils.consume(resEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }







    public static String doPostJson(String urlPath,String params){

        String result = "";

        HttpEntity resEntity = null;
        CloseableHttpResponse response = null;
        HttpPost httpPost = null;



        httpPost = new HttpPost(urlPath);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000).build();
        httpPost.setConfig(requestConfig);

        httpPost.setHeader("Content-type", "application/json;charset=UTF-8");

        try {
            StringEntity s = new StringEntity(params.toString(),"UTF-8");
            //s.setContentEncoding("UTF-8");
            s.setContentType("application/json");

            httpPost.setEntity(s);
            response = httpClientNoProxy.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                resEntity = response.getEntity();
                if (resEntity != null) {
                    try {
                        result = EntityUtils.toString(resEntity,"utf-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                        result =  JSON.parseObject(EntityUtils.toString(resEntity,"utf-8")).toJSONString();
                    }
                }
                logger.info("result = " + result);
            }else {
                logger.info("statusCode = " + statusCode);
            }
        } catch (Exception e) {
            logger.error("错误信息:",e);
        }finally {
            try {
                IOUtils.closeQuietly(response);
                httpPost.releaseConnection();
                EntityUtils.consume(resEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static void main(String[] args) {

        System.out.println(getAuthHeader());
        System.out.println();
    }
}
